package vn.allmobile.ambnews.utils;

import java.io.File;

import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import vn.allmobile.ambnews.R;
import vn.allmobile.ambnews.activities.sflash.SFlashActivity;
import vn.allmobile.ambnews.data.DbFeedAdapter;
import vn.allmobile.ambnews.data.DbHelper;
import vn.allmobile.ambnews.network.LoaderThread;
import vn.allmobile.ambnews.network.NetworkAPI;
import vn.allmobile.ambnews.network.SynchronizeRunable;
import vn.allmobile.ambnews.network.SynchronizeService;


import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.HttpClientImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;


import android.app.Application;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

public class GlobalApplication extends Application {
	

	

	private static Application _application;
	
	public static Application _()
	{

		return _application;
	}
	
	public GlobalApplication()
	{
		_application = this;
	}
	
	
	public static void startService()
	{
		Log.v("start service");
		SynchronizeService.cancelServive();
		_application.startService(new Intent(_application,SynchronizeService.class));		
	}
	
	
	private void addShortcut() {
	    //Adding shortcut for MainActivity 
	    //on Home screen
	    Intent shortcutIntent = new Intent(getApplicationContext(),
	            SFlashActivity.class);
	     
	    shortcutIntent.setAction(Intent.ACTION_MAIN);
	 
	    Intent addIntent = new Intent();
	    addIntent
	            .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Báo Mobi");
	    addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
	            Intent.ShortcutIconResource.fromContext(getApplicationContext(),
	                    R.drawable.ic_launcher));
	 
	    addIntent
	            .setAction("com.android.launcher.action.INSTALL_SHORTCUT");
	    addIntent
	    		.putExtra("duplicate", false);
	    getApplicationContext().sendBroadcast(addIntent);
	}
	
	
	public void onCreate()
	  {
	    super.onCreate();
	    if (NetworkAPI._dbHelper == null) {
	    	NetworkAPI._dbHelper = new DbHelper(this);
        }
	    
	    
	    System.setProperty("http.keepAlive", "true");
	    HttpParams params = new BasicHttpParams();
        // Turn off stale checking. Our connections break all the time anyway,
        // and it's not worth it to pay the penalty of checking every time.
        HttpConnectionParams.setStaleCheckingEnabled(params, false);
        // Default connection and socket timeout of 10 seconds. Tweak to taste.
        HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
        HttpConnectionParams.setSoTimeout(params, 10 * 1000);
        HttpConnectionParams.setSocketBufferSize(params, 8192);

        // Don't handle redirects -- return them to the caller. Our code
        // often wants to re-POST after a redirect, which we must do ourselves.
        HttpClientParams.setRedirecting(params, false);
        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0");
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

	    //File localFile = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "Android/data/vn.allmobile.ambnews/images");
        File localFile = StorageUtils.getCacheDirectory(getApplicationContext());	    	    	
	    	
	      ImageLoaderConfiguration localImageLoaderConfiguration = new ImageLoaderConfiguration.Builder(getApplicationContext())
	      	.threadPriority(Thread.NORM_PRIORITY + 4)
	      	.threadPoolSize(3)
	      	.memoryCache(new WeakMemoryCache())
	      	.denyCacheImageMultipleSizesInMemory()
	      	.discCache(new UnlimitedDiscCache(localFile))
	      	.discCacheFileNameGenerator(new Md5FileNameGenerator())	      	
	      	.tasksProcessingOrder(QueueProcessingType.FIFO)
	      	.enableLogging()
	      	.imageDownloader(new HttpClientImageDownloader(getApplicationContext(),new DefaultHttpClient(manager, params)))
	      	.build();
	      ImageLoader.getInstance().init(localImageLoaderConfiguration);
	      
	      if(PreferenceManager.isFirstTime())
	      {
	    	  //addShortcut();
	    	  PreferenceManager.init();	    	 
	      }
	    
        Thread localThread = new Thread(new SynchronizeRunable());
	    localThread.setName("StartServicesThread");
	    localThread.setDaemon(true);
	    localThread.setPriority(10); 
	    localThread.start();
		
	  }	
	
	public synchronized static SQLiteDatabase getDB() {
        return NetworkAPI._dbHelper.getWritableDatabase();
    }
	
	/* (non-Javadoc)
	 * @see android.app.Application#onLowMemory()
	 */
	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
		
		
		
		
	}
}
